package main


import (
  "fmt"
  "time"
)

type Cert struct {
    CertID           string   `json:"certid"`
    Name             string   `json:"name"`
    UID              int64    `json:"uid"`
    CommonName       string   `json:"common_name"`
    DNSNames         []string `json:"dnsnames"`
    CreateTime       int64    `json:"create_time"`
    NotBefore        int64    `json:"not_before"`
    NotAfter         int64    `json:"not_after"`
    OrderID          string   `json:"orderid"`
    ProductShortName string   `json:"product_short_name"`
    ProductType      string   `json:"product_type"`
    CertType         string   `json:"cert_type"`
    Encrypt          string   `json:"encrypt"`
    EncryptParameter string   `json:"encryptParameter"`
    Enable           bool     `json:"enable"`
    ChildOrderID     string   `json:"child_order_id"`
    State            string   `json:"state"`
    AutoRenew        bool     `json:"auto_renew"`
    Renewable        bool     `json:"renewable"`
    CertStr          string   `json:"ca"`
    KeyStr           string   `json:"pri"`
}

// 证书是否已过期
func (c *Cert) IsExpired() bool {
  return  time.Now().After(time.Unix(c.NotAfter, 0))
}

func (c *Cert) Print() {
  loc, _ := time.LoadLocation("Asia/Shanghai")
  fmt.Printf("CertID: %s\nName: %s\nCommonName: %s\nCreateTime: %s\nNotBefore: %s\nNotAfter: %s\n",
    c.CertID, c.Name, c.CommonName,
    time.Unix(c.CreateTime, 0).In(loc).Format("2006-01-02 15:04:05"),
    time.Unix(c.NotBefore, 0).In(loc).Format("2006-01-02 15:04:05"),
    time.Unix(c.NotAfter, 0).In(loc).Format("2006-01-02 15:04:05"),
  )
}

func (c *Cert) CertState(days int) (state string) {
  t := time.Now()
  if t.Before(time.Unix(c.NotBefore, 0)) {
    state = "Pending"  // 还未生效
  } else if t.After(time.Unix(c.NotAfter, 0)) {
    state = "Expired"  // 已过期
  } else if t.Add(time.Duration(days) * 24 * time.Hour).After(time.Unix(c.NotAfter, 0)) {
    state = "Expiring" // days 天后过期
  } else {
    state = "Valid"    // 有效期内
  }
  return state
}

func (c *Cert) Printx() {
  loc, _ := time.LoadLocation("Asia/Shanghai")
  state := c.CertState(14)
  fmt.Printf("%-24s %-8s %-35s %-25s %-19s %-19s %s\n",
    c.CertID, state, c.Name, c.CommonName,
    time.Unix(c.CreateTime, 0).In(loc).Format("2006-01-02 15:04:05"),
    time.Unix(c.NotBefore, 0).In(loc).Format("2006-01-02 15:04:05"),
    time.Unix(c.NotAfter, 0).In(loc).Format("2006-01-02 15:04:05"),
  )
}

func (c *Cert) PrintxHeader() {
  fmt.Printf("%-24s %-8s %-35s %-25s %-19s %-19s %s\n", 
    "CertID", "State", "Name", "CommonName", "@Create", "@NotBefore", "@NotAfter")
}

func (c *Cert) PrintKey() {
  fmt.Println(c.KeyStr)
}

func (c *Cert) PrintCert() {
  fmt.Println(c.CertStr)
}

